package com.tianhui.consignortwofei.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.fgs.common.manager.ActivityManager;
import com.fgs.common.utils.LogUtil;
import com.fgs.common.webViewInter.OpenWeb;
import com.fgs.common.webViewInter.PrivacyPolicyWebInfo;
import com.fgs.common.webViewInter.UserAgreementWebInfo;
import com.google.gson.reflect.TypeToken;
import com.tianhui.consignortwofei.BuildConfig;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseActivity;
import com.tianhui.consignortwofei.base.BaseFragment;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.interf.OnLoginFragmentSwitchListener;
import com.tianhui.consignortwofei.manager.EventBusManage;
import com.tianhui.consignortwofei.manager.SharedPreferenceManager;
import com.tianhui.consignortwofei.mvp.contract.LoginContract;
import com.tianhui.consignortwofei.mvp.model.enty.CaptchaInfo;
import com.tianhui.consignortwofei.mvp.model.enty.LoginInfo;
import com.tianhui.consignortwofei.mvp.presenter.LoginPresenter;
import com.tianhui.consignortwofei.mvp.ui.fragment.login.CodeFragment;
import com.tianhui.consignortwofei.mvp.ui.fragment.login.PasswordFragment;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.net.JsonUtil;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author fgs
 * @date 2019/5/29
 **/
public class LoginActivityNew extends BaseActivity<LoginContract.View, LoginContract.Presenter>
        implements LoginContract.View {

    @BindView(R.id.activity_login_checkBox)
    CheckBox checkBox;

    @BindView(R.id.activity_login_loginMethodButton)
    Button loginMethodButton;

    @BindView(R.id.activity_login_switchUrlTextView)
    TextView switchUrlTextView;

    @BindView(R.id.wv_captcha)
    WebView wv_captcha;

    private FragmentManager fragmentManager;
    private Fragment currentFragment;
    private PasswordFragment passwordFragment;
    private CodeFragment codeFragment;

    private boolean isPasswordLogin = true;
    private boolean isCheck = false;

    private OnLoginFragmentSwitchListener onCurrentFragmentSwitchListener;
    private OnLoginFragmentSwitchListener onSwitchFragmentSwitchListener;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login_new;
    }

    @Override
    public LoginContract.Presenter createPresenter() {
        return new LoginPresenter(this);
    }

    @Override
    public LoginContract.View createView() {
        return this;
    }

    @Override
    public boolean isShowToolbar() {
        return false;
    }

    @Override
    public void init() {


        passwordFragment = new PasswordFragment();
        codeFragment = new CodeFragment();
        fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().add(R.id.activity_login_containerFrameLayout, passwordFragment).commit();
        fragmentManager.beginTransaction().add(R.id.activity_login_containerFrameLayout, codeFragment).commit();
        fragmentManager.beginTransaction().hide(codeFragment).commit();
        currentFragment = passwordFragment;
        onSwitchFragmentSwitchListener = passwordFragment;

        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isCheck = isChecked;
                setCheckStatus(isChecked);
            }
        });

        if (BuildConfig.DEBUG){
            switchUrlTextView.setVisibility(View.VISIBLE);
        }else {
            switchUrlTextView.setVisibility(View.GONE);
        }


        initWebView();

    }

    private void setCheckStatus(boolean isChecked) {
        if (onSwitchFragmentSwitchListener != null) {
            onSwitchFragmentSwitchListener.setIsChecked(isChecked);
        }
    }

    private void switchFragment(Fragment fragment) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (!fragment.isAdded()) {
            fragmentTransaction.hide(currentFragment);
            fragmentTransaction.add(R.id.activity_login_containerFrameLayout, fragment);
        } else {
            fragmentTransaction.hide(currentFragment);
            fragmentTransaction.show(fragment);
        }
        fragmentTransaction.commit();

        currentFragment = fragment;
    }

    @OnClick(R.id.activity_login_loginMethodButton)
    public void loginMethod() {


        if (isPasswordLogin) {
            switchFragment(codeFragment);
            onCurrentFragmentSwitchListener = passwordFragment;
            loginMethodButton.setText(getResources().getString(R.string.string_password_login));
            onSwitchFragmentSwitchListener = codeFragment;

        } else {
            switchFragment(passwordFragment);
            loginMethodButton.setText(getResources().getString(R.string.string_code_login));
            onCurrentFragmentSwitchListener = codeFragment;
            onSwitchFragmentSwitchListener = passwordFragment;

        }


        setCheckStatus(isCheck);
        onSwitchFragmentSwitchListener.onFragmentSwitch(onCurrentFragmentSwitchListener.getPhone());
        isPasswordLogin = !isPasswordLogin;
    }


    @OnClick(R.id.activity_login_registerLinearLayout)
    public void register() {
        openActivityForResult(RegisterActivity.class);
    }

    @OnClick(R.id.activity_login_forgetPasswordTextView)
    public void forgetPasswordTip() {
        openActivity(ForgetPasswordActivity.class);
    }

    @OnClick(R.id.activity_login_userAgreementTextView)
    public void userAgreement() {
        OpenWeb openWeb = new OpenWeb();
        openWeb.openWebView(this, new UserAgreementWebInfo());
    }


    @OnClick(R.id.activity_login_privacyPolicyTextView)
    public void privacyPolicy() {
        OpenWeb openWeb = new OpenWeb();
        openWeb.openWebView(this, new PrivacyPolicyWebInfo());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == 1) {
            if (data != null) {
                Bundle bundle = data.getExtras();
                if (bundle != null && !bundle.isEmpty()) {
                    String phone = bundle.getString(KeyValue.KEY_PHONE);
                    EventBusManage.refreshPhone(phone);
                }
            }
        }

    }

    @Override
    public BaseFragment createFragment() {
        return null;
    }

    @Override
    public void result(LoginInfo info) {

    }

    @Override
    public void authCodeResult() {

    }


    @OnClick(R.id.activity_login_switchUrlTextView)
    public void switchUrl() {
        showSwitchDialog();
    }

    private void showSwitchDialog() {
        new MaterialDialog.Builder(getContext())
                .title("切换地址")
                .items(R.array.array_base_url)
                .itemsCallbackSingleChoice(
                        -1,
                        new MaterialDialog.ListCallbackSingleChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {

                                if (which == 0) { // demo
                                    SharedPreferenceManager.getInstance().setBaseUrl(text.toString());
                                    SharedPreferenceManager.getInstance().setBaseWebUrl(text.toString());
                                    SharedPreferenceManager.getInstance().setBaseImageUrl("http://demo.tianhuihaojun.com/picustomer/");
                                } else if (which == 1) { //cnor
                                    SharedPreferenceManager.getInstance().setBaseUrl(text.toString());
                                    SharedPreferenceManager.getInstance().setBaseWebUrl(text.toString());
                                    SharedPreferenceManager.getInstance().setBaseImageUrl("https://cnor.tianhuihaojun.com/picustomer/");
                                } else if (which == 6){
                                    SharedPreferenceManager.getInstance().setBaseUrl(text.toString());
                                    SharedPreferenceManager.getInstance().setBaseImageUrl("http://192.168.3.216:8082/picture/getImgStream?idFile=");
                                }else {
                                    SharedPreferenceManager.getInstance().setBaseUrl(text.toString());
                                }
                                ActivityManager.getInstance().finishAllActivity();
                                System.exit(0);
                                return true;
                            }
                        })
                .show();
    }



    //验证码
    private void initWebView() {
        //如果要做成弹窗式的，那么这个webview就要设置成透明的，否则webview不透明会挡住主页面的布局
        wv_captcha.setBackgroundColor(0);
        WebSettings webSettings = wv_captcha.getSettings();
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        // 禁用缓存
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        wv_captcha.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        // 开启js支持
        webSettings.setJavaScriptEnabled(true);
        wv_captcha.addJavascriptInterface(new JsBridge(), "jsBridge");
        // 也可以加载本地html(webView.loadUrl("file:///android_asset/xxx.html"))
        //zh-hk，ja，en

//  wv_captcha.loadUrl("file:///android_asset/tencenweb.html?lan=zh-hk");
//        wv_captcha.loadUrl("file:///android_asset/tencenweb.html");


    }

    public class JsBridge {

        @JavascriptInterface
        public void getData(String data) {
            //回调结果：{"ret":2,"randstr":"","ticket":""}

            LogUtil.print("fei", data);
                CaptchaInfo info = JsonUtil.fromJson(data, new TypeToken<CaptchaInfo>() {
                }.getType());
                if (info.ret == 0) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // 更新UI的代码
                            wv_captcha.setVisibility(View.GONE);
                        }
                    });
                    if (isPasswordLogin) {
                        passwordFragment.sendYanZheng(info);
                    }else {
                        codeFragment.sendYanZheng(info);
                    }
//                    String phone = phoneEditText.getText().toString().trim();
//                    info.mobile = "+86" + phone;
//                    info.action = "login";
//                    getPresenter().getAuthCode(info, true);
                }else if (info.ret == 2){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // 更新UI的代码
                            wv_captcha.setVisibility(View.GONE);
                        }
                    });
                }
        }
    }


    public void getYanZheng() {
        wv_captcha.setVisibility(View.VISIBLE);
        wv_captcha.loadUrl("file:///android_asset/tencenweb.html?lan=zh-hk");

    }



}
